package net.asfun.jvalog.http;

import java.io.IOException;
import java.util.logging.Level;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import static net.asfun.jvalog.misc.Log.logger;
import net.asfun.jvalog.action.CommentAction;
import net.asfun.jvalog.action.UserAction;
import net.asfun.jvalog.except.InteractException;
import net.asfun.jvalog.misc.ThreadHelper;

public class ActiveServlet extends HttpServlet {

	private static final long serialVersionUID = 200907052147L;

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		String action = RequestUtil.getRequiredParam(req, "act");
		try {
			ThreadHelper.startup();
			if ("comment".equalsIgnoreCase(action)) {
				CommentAction ca = new CommentAction();
				ca.add(req, resp);
			} else if ("login".equalsIgnoreCase(action)) {
				UserAction ua = new UserAction();
				ua.login(req, resp);
			} else if ("logout".equalsIgnoreCase(action)) {
				UserAction ua = new UserAction();
				ua.logout(req, resp);
			} else {
				resp.sendError(403);
			}
		} catch (InteractException ie) {
			//TODO treat ajax & normal diffentily
			String message = null;
			try {
				JSONObject json = new JSONObject();
				json.put("type", "error");
				json.put("message", ie.getMessage());
				message = json.toString();
			} catch (JSONException e) {
				message = "{type:\"error\",message:\"json error\"}";
				logger.log(Level.SEVERE, e.getMessage(), e);
			}
			resp.setContentType("text/plain");
			resp.getWriter().println(message);
		} catch (Exception e) {
			logger.log(Level.INFO, e.getMessage(), e);
			resp.sendRedirect("/jva.log");
		}
		ThreadHelper.shutdown();
	}

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.sendError(403);
	}
}
